/*
 * Copyright 2011-2012 by The Regents of the University of California Licensed
 * under the Apache License, Version 2.0 (the "License"); you may not use this
 * file except in compliance with the License. you may obtain a copy of the
 * License from
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package edu.ucsd.db.bassarisk.query.bindingtree.visitor;

import edu.ucsd.db.bassarisk.query.bindingtree.BindingTreeElements.BindingTreeEdge;
import edu.ucsd.db.bassarisk.query.bindingtree.BindingTreeElements.ChoiceNode;
import edu.ucsd.db.bassarisk.query.bindingtree.BindingTreeElements.EstablishingNode;
import edu.ucsd.db.bassarisk.treepattern.EdgeFunction;

public class AnswerNodeCollectionTraversal implements
    BindingTreeVisitor<BindingTreeEdge, Void> {
  @Override
  public BindingTreeEdge visitBindingTreeEdge(final BindingTreeEdge edge,
                                              final Void args) {
    if (edge.functions().contains(EdgeFunction.Values)) {
      BindingTreeEdge subReturn = edge.tailNode().accept(this, args);
      if (subReturn != null) {
        return subReturn;
      } else {
        return edge;
      }
    } else {
      return null;
    }
  }

  @Override
  public BindingTreeEdge visitChoiceNode(final ChoiceNode element, final Void args) {
    // The answer node can not be under a choice node.
    return null;
  }

  @Override
  public BindingTreeEdge visitEstablishingNode(final EstablishingNode node,
                                               final Void args) {
    BindingTreeEdge returns = null;
    for (BindingTreeEdge edge : node.children()) {
      if (edge.functions().contains(EdgeFunction.Values)) {
        BindingTreeEdge subReturn = edge.tailNode().accept(this, args);
        if (subReturn != null && returns != null) {
          throw new RuntimeException("More than one find target detected.");
        } else if (subReturn != null) {
          returns = subReturn;
        } else {
          returns = edge;
        }
      }
    }
    return returns;
  }
}
